﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
namespace textimport
{
    class Program
    {
        static string root = @"E:\game\test\oreimou\";
        static string fobj = @"obj\";
        static string ftrans = @"trans\";
        static string fnrans = @"trans_out\";
        static string fnbj = @"obj_new\";
        static void Main(string[] args)
        {
            string[] BinFiles = Directory.GetFiles(root + fobj);
            foreach (string BinFile in BinFiles)
            {
                obj_import(BinFile);
            }
            //res_import();
            Console.WriteLine("Import Complete");
        }

        private static void obj_import(string BinFile)//文本导入OBJ
        {
            string fn = Path.GetFileName(BinFile);

            string TextFile = root + ftrans + fn + ".txt";
            if (!File.Exists(TextFile)) return;
            byte[] buf=new byte[1024];

            if (!Directory.Exists(root+fnbj))
                Directory.CreateDirectory(root+fnbj);
            if (!Directory.Exists(root + fnrans))
                Directory.CreateDirectory(root + fnrans);

            FileStream fsob = File.Open(BinFile, FileMode.Open, FileAccess.Read);
            FileStream fsnb = File.Open(root+fnbj+fn, FileMode.Create, FileAccess.Write);
            FileStream fstx = File.Open(TextFile, FileMode.Open, FileAccess.Read);
            FileStream fstn = File.Open(root+fnrans+fn+".txt", FileMode.Create, FileAccess.Write);
            BinaryReader brob = new BinaryReader(fsob);
            BinaryWriter bwnb = new BinaryWriter(fsnb);
            StreamReader sr = new StreamReader(fstx);
            StreamWriter sw = new StreamWriter(fstn);

            if (brob.Read(buf, 0, 0x30) != 0x30)
            {
                Console.WriteLine(root + fobj + BinFile + "错误，读取失败");
                throw new Exception(root + fobj + BinFile + "错误，读取失败");
            }

            bwnb.Write(buf, 0, 0x30);
            int count = 0, linecount=0;
            while (true)
            {
                count++;
                if (brob.Read(buf, 0, 4) != 4) break;
                int size = BitConverter.ToInt32(buf, 0);

                brob.Read(buf, 4, size - 4);

                int type = BitConverter.ToInt16(buf, 4);
                //Console.WriteLine(String.Format("{0} {1} {2}", count, size, type));
                if (type == 0x64 || type == 0x68)
                {
                    linecount++;
                    int strlen = BitConverter.ToInt32(buf, 11);
                    char[] str = Encoding.Unicode.GetChars(buf, 15, strlen * 2);
                    //parentchk(fsob.Name, count, str);
                    sw.WriteLine(string.Format("{0}", count));
                    sw.WriteLine(new string(str));
                    string rs = sr.ReadLine();
                    rs = CutAddr(rs);
                    parentchk(fstx.Name, linecount, rs);
                    sw.WriteLine(rs);
                    sr.ReadLine();
                    sw.WriteLine();

                    byte[] btxt = Encoding.Unicode.GetBytes(rs);

                    strlen = rs.Length;
                    byte[] bstrlen = BitConverter.GetBytes(strlen);

                    size = 15 + btxt.Length;
                    size += 4;
                    size = size + (16 - size % 16);
                    for (int i = 15 + btxt.Length; i < size; i++)
                        buf[i] = 0;
                    byte[] bsize = BitConverter.GetBytes(size);

                    bsize.CopyTo(buf, 0);
                    bstrlen.CopyTo(buf, 11);
                    btxt.CopyTo(buf, 15);

                    bwnb.Write(buf, 0, size);
                }
                else if (type == 0x2bc ||type==0x12e)
                {
                    linecount++;
                    int strlen = BitConverter.ToInt32(buf, 6);
                    char[] str = Encoding.Unicode.GetChars(buf, 10, strlen * 2);

                    sw.WriteLine(string.Format("{0}", count));
                    sw.WriteLine(new string(str));
                    string rs = sr.ReadLine();
                    rs = CutAddr(rs);
                    sw.WriteLine(rs);
                    sr.ReadLine();
                    sw.WriteLine();

                    byte[] btxt = Encoding.Unicode.GetBytes(rs);
                    strlen = rs.Length;
                    byte[] bstrlen=BitConverter.GetBytes(strlen);
                    size = 10 + btxt.Length;
                    size += 4;
                    size = size + (16 - size % 16);
                    for (int i = 10 + btxt.Length; i < size; i++)
                        buf[i] = 0;
                    byte[] bsize = BitConverter.GetBytes(size);
                    bsize.CopyTo(buf, 0);
                    bstrlen.CopyTo(buf, 6);
                    btxt.CopyTo(buf, 10);

                    bwnb.Write(buf,0,size);
                }
                else
                {
                    bwnb.Write(buf, 0, size);
                }

                //if (!fsob.CanRead) break;
            }
            //comparing line
            
            int linecount2=0;
            sr.BaseStream.Seek(0, SeekOrigin.Begin);
            while (!sr.EndOfStream)
            {
                sr.ReadLine();
                sr.ReadLine();
                linecount2++;
            }
            if (linecount2 != linecount)
            {
                Console.WriteLine(String.Format("{0} {1}", linecount, linecount2));
                throw new Exception(BinFile);
            }
            
            Console.WriteLine(BinFile);
            sw.Close();
            bwnb.Close();
            brob.Close();
            sr.Close();
        }

        private static void parentchk(string Name, int count, string str)
        {
            int pcnt = 0, pcnt2 = 0;
            if (str.Contains(',')) throw new Exception(Name + count.ToString());
            foreach (char ch in str) 
            {
                if (ch == '｛')
                    pcnt++;
                if (ch == '｝') pcnt--;
                if (pcnt < 0 || ch=='{' || ch=='}')
                    throw new Exception(Name + count.ToString());
            }
            if (pcnt != 0) throw new Exception(Name + count.ToString());
            bool mao=true;
            foreach (char ch in str)
            {
                if (ch == '《')
                {
                    pcnt2++;
                    mao = false;
                }
                if (ch == '》') pcnt2--;
                if (pcnt2 < 0 || pcnt2 > 1)
                    throw new Exception(Name + count.ToString());
                if (pcnt2 == 1 && ch == '：')
                    mao = true;
            }
            if (pcnt2 != 0 || !mao) throw new Exception(Name + count.ToString());
        }


        private static string CutAddr(string rs)
        {
            int cps = rs.IndexOf(',');
            rs = rs.Substring(cps+1);
            cps = rs.IndexOf(',');
            rs = rs.Substring(cps+1);
            return rs;
        }
    }
}
